import 'dart:async';

import 'package:chathouse/constant/app_constant.dart';
import 'package:chathouse/model/expert.dart';
import 'package:chathouse/pages/expert/charts_page.dart';
import 'package:chathouse/pages/expert/edit_expert_service.dart';
import 'package:chathouse/pages/expert/service_list_page.dart';
import 'package:chathouse/pages/expert/wallet_page.dart';
import 'package:chathouse/public/event_bus.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/log.dart';
import 'package:chathouse/web_socket/web_socket_channel.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../push/chat_house_push.dart';
import 'masterplate_page.dart';

class Homepage extends StatefulWidget {
  const Homepage({Key? key}) : super(key: key);

  @override
  _HomepageState createState() => _HomepageState();
}

class _HomepageState extends State<Homepage>
    with AutomaticKeepAliveClientMixin {
  Expert? info;
  Expert? member;
  StreamSubscription? refreshSubscription;

  @override
  void initState() {
    super.initState();
    loadMemberInfo();
    loadBalance();
    refreshSubscription = eventBus.on<UpdateMemberInfo>().listen((event) {
      loadBalance();
      loadMemberInfo();
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  void loadMemberInfo() {
    Obj.showLoading();
    Apis.expertInfo()
        // ignore: avoid_print
        .then((response) => {
              Obj.dismissLoading(),
              setState(() {
                var data = response?.data["data"];
                if (data != null) {
                  info = Expert.fromJson(data);
                  setState(() {});
                }
              })
            })
        .onError((error, stackTrace) =>
            {Obj.dismissLoading(), print("expertInfo error"), print(error)});
  }

  void loadBalance() {
    Obj.showLoading();
    Apis.getMembersInfo()
        // ignore: avoid_print
        .then((response) => {
              Obj.dismissLoading(),
              setState(() {
                var data = response?.data["data"];
                member = Expert.fromJson(data);
                setState(() {});
              })
            })
        .onError((error, stackTrace) => {
              Obj.dismissLoading(),
              print("getMembersInfo error"),
              print(error)
            });
  }

  Widget item(var imageName, var name, var width, var height) {
    return InkWell(
      onTap: () => {
        if (imageName == Res.expert_service)
          {
            eventBus.fire(UpdateRootIndexEvent(1)),
          },
        if (imageName == Res.expertMine_orders)
          {
            eventBus.fire(UpdateRootIndexEvent(4)),
          },
        if (imageName == Res.expert_ben)
          {
            Get.to(const Masterplate()),
          },
        if (imageName == Res.expert_orders) {
          Get.to(const ChartsPage()),
        }
      },
      child: Container(
        decoration: BoxDecoration(
            color: Styles.mainColor,
            borderRadius: BorderRadius.circular(Styles.magin_16)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ImageUtils.image(imageName, width: width, height: height),
            Text(name,
                    style: getTextStyle(20.sp,
                        fontType: FontType.BOLD, color: Colors.white))
                .setContainer(margin: EdgeInsets.only(top: 4))
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: Colors.white,
      body: ListView(
        children: [
          Container(
            margin: EdgeInsets.only(top: Styles.magin_24),
            child: SizedBox(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Stack(
                    children: [
                      Text('歡迎',
                              style: getTextStyle(30.sp,
                                  fontType: FontType.BOLD, color: Colors.black))
                          .setContainer(
                              margin: EdgeInsets.only(left: Styles.magin_24)),
                      Text(member?.membersName ?? "",
                              style: getTextStyle(20.sp,
                                  fontType: FontType.BOLD, color: Colors.black))
                          .setContainer(
                              margin: EdgeInsets.only(
                                  left: Styles.magin_24, top: 50.w)),
                    ],
                  ),
                  (member?.memberImage ?? "").isEmpty ? ImageUtils.image('assets/images/expert_avatar.png',
                      width: 80.w,
                      height: 80.w,
                      imageType: ImageType.ASSET,
                      radius: 40.w)
                      .setContainer(
                      margin: EdgeInsets.only(right: Styles.magin_24)) : ImageUtils.image(member?.memberImage ?? '',
                          width: 80.w,
                          height: 80.w,
                          imageType: ImageType.NETWORK,
                          radius: 40.w)
                      .setContainer(
                          margin: EdgeInsets.only(right: Styles.magin_24)),
                ],
              ),
            ),
          ),
          Text("金幣餘額:${info?.balance ?? "0"}個",
                  style: getTextStyle(30.sp,
                      fontType: FontType.BOLD, color: Styles.mainColor))
              .setContainer(
                  margin: EdgeInsets.only(
                      left: Styles.magin_24, top: Styles.magin_24)),
          Container(
            margin: EdgeInsets.only(
                left: Styles.magin_24,
                right: Styles.magin_24,
                top: Styles.magin_16),
            padding: EdgeInsets.symmetric(horizontal: Styles.magin_12),
            height: 135.w,
            decoration: BoxDecoration(
                color: Styles.FF9800,
                borderRadius: BorderRadius.circular(Styles.magin_16)),
            child: Row(
              // mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ImageUtils.image(
                  Res.awesome_wallet,
                  width: 110.w,
                  height: 96.w,
                ),
                const SizedBox(
                  width: 16,
                ),
                Text('管理金幣銀包',
                    style: getTextStyle(30.sp,
                        fontType: FontType.BOLD, color: Colors.white)),
              ],
            ),
          ).setOnClickListener(() {
            Get.to(const WealletPage());
          }),
          Container(
            margin: EdgeInsets.only(
                left: Styles.magin_24,
                right: Styles.magin_24,
                top: Styles.magin_12),
            child: GridView.count(
              crossAxisCount: 2,
              primary: false,
              shrinkWrap: true,
              crossAxisSpacing: 12.w,
              mainAxisSpacing: 12.w,
              childAspectRatio: 185.0 / 153.0,
              children: [
                item(Res.expert_service, "服務需求", 78.w, 78.w),
                item(Res.expertMine_orders, "我的項目", 103.w, 78.w),
                item(Res.expert_ben, "報價單模版", 68.w, 78.w),
                item(Res.expert_orders, "接單產量", 82.w, 78.w),
              ],
            ),
          )
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
